import allure
from responses_validator import validator

from common.logger_util import LoggerUtil
from common.request_util import RequestUtil

logger = LoggerUtil().get_logger()


class AssertUtil:
    def __init__(self):
        self.req_u = RequestUtil()

    @allure.step("接口断言")
    def res_assert(self, res, kwargs):
        for key, value in kwargs.items():
            match key:
                case 'eq':
                    actual_value = value["actual_value"]
                    expect_value = value["expect_value"]
                    if "$." in actual_value:
                        actual_value = self.req_u.jsonpath_extract(res.json(), actual_value)
                    elif "(.*?)" in actual_value or "(.+?)" in actual_value:
                        actual_value = self.req_u.re_extract(res, actual_value)
                    else:
                        actual_value = actual_value
                    assert actual_value == expect_value,logger.error(f"接口断言断言失败, 预期结果：{expect_value},实际结果：{actual_value}")
                case "contain":
                    if value["contain_value"]:
                        assert  value["contain_value"] in res.text, logger.error(f"接口断言断言失败,接口响应不包含{value["contain_value"]}")
                case "response_validate":
                    if value:
                        validator(res,**eval(value))


